package linked;

import java.util.Objects;

/**
 * @author
 * @date 2025/5/19 19:54
 */
public class 两两相交 {
    public static void main(String[] args) {
        LinkedNode header01 = new LinkedNode("header01");
        LinkedNode interactNode = new LinkedNode("D");
        LinkedList linkedList = new LinkedList(header01);
        linkedList.add(new LinkedNode("A"));
        linkedList.add(new LinkedNode("B"));
        linkedList.add(new LinkedNode("C"));
        linkedList.add(interactNode);
        linkedList.add(new LinkedNode("E"));
        LinkedNode header02 = new LinkedNode("header02");
        LinkedList linkedList1 = new LinkedList(header02);
        linkedList1.add(new LinkedNode("a"));
        linkedList1.add(new LinkedNode("b"));
        linkedList1.add(interactNode);

        LinkedNode intersectionNode = getIntersectionNode(linkedList, linkedList1);
        if(intersectionNode!=null){
            System.out.println(intersectionNode.value);
        }else {
            System.out.println((Object) null);
        }
    }


    /**
     * 获取两个节点的长度差值，然后使用快慢指针即可
     * @param linkedList01
     * @param linkedList02
     */
    public static LinkedNode getIntersectionNode(LinkedList linkedList01,LinkedList linkedList02){
        // 获取链表1的长度
        int size01 = 0;
        LinkedNode temp01 = linkedList01.header;
        while (temp01!=null){
            size01++;
            temp01= temp01.next;
        }

        LinkedNode temp02 = linkedList02.header;
        int size02 = 0;
        while (temp02!=null){
            size02++;
            temp02 = temp02.next;
        }

        LinkedNode  cur01 = linkedList01.header;
        LinkedNode cur02  = linkedList02.header;

        if (size01>size02) {
            // 链表1长
            int diff = size01- size02;
            while (diff>0){
                cur01 = cur01.next;
                diff--;
            }
        }else{
            // 链表二2
            int diff = size02-size01;
            while (diff>0){
                cur02 = cur02.next;
                diff--;
            }
        }
        while (cur01!=null&&cur02!=null){
            if(Objects.equals(cur01,cur02)){
                return cur01;
            }
            cur01 = cur01.next;
            cur02 = cur02.next;
        }
        return null;
    }
}
